package user

import (
	"common/mildware"
	"common/models"
	"common/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"strings"
)

func (h UHandler) AddFriends(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.AddFriendReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:AddFriends with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:AddFriends with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//获得ID
	ID, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("User :AddFriends mildware.GetCyrrentUserID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//添加用户
	code, err := h.addFriend(ID, req.FriendID)
	if err != nil {
		zap.L().Error("User :AddFriends mildware.GetCyrrentUserID err", zap.Error(err))
		resp.SendCode(c, code)
	}
	code, err = h.addFriend(req.FriendID, ID)
	if err != nil {
		zap.L().Error("User :AddFriends mildware.GetCyrrentUserID err", zap.Error(err))
		resp.SendCode(c, code)
	}
	resp.SendSuccess(c)
}
func (h UHandler) addFriend(fromID, toID string) (code int64, err error) {
	//获得用户的信息
	exist, info, err := h.M.UserCheckId(fromID)
	if err != nil {
		return
	}
	if !exist {
		code = models.CodeUserNotExist
		return
	}
	friends := strings.Split(info.Friends, "|")
	//判断是否存在
	fExist, _ := models.CheckList(friends, toID)
	if fExist {
		code = models.CodeUserNotExist
		return
	}
	if info.Friends == "|" {
		info.Friends = toID
	} else {
		info.Friends = models.AddListToString(friends, toID)
	}
	//更新用户信息
	if err = h.M.UserUpdateById(info); err != nil {
		code = models.CodeServerBusy
	}
	return
}
